package com.ssy.lingxi.search.serviceImpl;

import com.ssy.lingxi.common.constant.Constants;
import com.ssy.lingxi.search.api.model.request.AreaRequest;
import com.ssy.lingxi.search.api.model.request.AttributeRequest;
import com.ssy.lingxi.search.api.model.request.OrderRequest;
import com.ssy.lingxi.search.service.IOrderService;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 订单服务实现类
 * @author jw.chen
 * @version 2.0.0
 * @date 2020/6/22
 */
@Service
public class OrderServiceImpl implements IOrderService {

    @Resource
    private RestHighLevelClient restHighLevelClient;

    /**
     * 查询会员
     * @param orderRequest
     * @return
     */
    @Override
    public List<Long> getMemberIdList(OrderRequest orderRequest) {
        List<Long> categoryIdList = orderRequest.getCategoryIdList();
        List<AreaRequest> areaRequestList = orderRequest.getAreaRequestList();
        List<AttributeRequest> attributeList = orderRequest.getAttributeList();

        // 查询条件
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();

        //区域搜索
        if(areaRequestList != null && !areaRequestList.isEmpty()){
            BoolQueryBuilder areaQueryBuilder = QueryBuilders.boolQuery();
            areaRequestList.forEach(areaRequest -> {
                String provinceCode = areaRequest.getProvinceCode();
                String cityCode = areaRequest.getCityCode();

                BoolQueryBuilder query = QueryBuilders.boolQuery();
                // 拼接省份搜索
                if(StringUtils.isNotEmpty(provinceCode)){
                    BoolQueryBuilder province = QueryBuilders.boolQuery().must(QueryBuilders.matchQuery("isAllArea", false)).must(QueryBuilders.matchQuery("commodityAreaList.provinceCode", provinceCode));
                    query.must(QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("isAllArea", true)).should(province));
                }
                // 拼接城市搜索
                if(StringUtils.isNotEmpty(cityCode)){
                    BoolQueryBuilder city = QueryBuilders.boolQuery().must(QueryBuilders.matchQuery("commodityAreaList.isAllCity", false)).must(QueryBuilders.matchQuery("commodityAreaList.cityCode", cityCode));
                    query.must(QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("isAllArea", true)).should(QueryBuilders.matchQuery("commodityAreaList.isAllCity", true)).should(city));
                }
                areaQueryBuilder.should(query);
            });
            queryBuilder.must(areaQueryBuilder);
        }

        // 拼接平台后台分类搜索
        if(categoryIdList != null && !categoryIdList.isEmpty()){
            BoolQueryBuilder categoryQueryBuilder = QueryBuilders.boolQuery();
            categoryIdList.forEach(categoryId -> categoryQueryBuilder.should(QueryBuilders.queryStringQuery("customerCategory.category.fullId:*" + String.format(Constants.CATEGORY_FULL_ID_NUM, categoryId) + "*")));
            queryBuilder.must(categoryQueryBuilder);
        }
        // 拼接属性搜索
        if(attributeList != null && !attributeList.isEmpty()){
            BoolQueryBuilder attributeQueryBuilder = QueryBuilders.boolQuery();
            attributeList.forEach(attributeRequest -> {
                Long attributeId = attributeRequest.getAttributeId();
                String attributeValue = attributeRequest.getAttributeValue();
                BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
                if(attributeId != null && attributeId > 0){
                    boolQueryBuilder.must(QueryBuilders.matchQuery("unitPricePicList.attributeAndValueList.customerAttribute.attribute.id", attributeId));
                }
                boolQueryBuilder.must(QueryBuilders.matchQuery("unitPricePicList.attributeAndValueList.customerAttributeValue.attributeValue.value", attributeValue));
                attributeQueryBuilder.should(boolQueryBuilder);
            });
            queryBuilder.must(attributeQueryBuilder);
        }

        //构建查询条件
        SearchRequest search = new SearchRequest(Constants.ES_COMMODITY_INDEX);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.size(0);
        searchSourceBuilder.query(queryBuilder);
        //分组
        TermsAggregationBuilder aggregationMemberId = AggregationBuilders.terms("group_memberId").field("memberId").size(1200000);
        searchSourceBuilder.aggregation(aggregationMemberId);
        search.source(searchSourceBuilder);
        try{
            Set<Long> memberIdSet = new HashSet<>();
            //搜索
            SearchResponse searchResponse = restHighLevelClient.search(search, RequestOptions.DEFAULT);
            Aggregations aggregations = searchResponse.getAggregations();
            if(aggregations != null){
                Terms brandTerms = aggregations.get("group_memberId");
                List<? extends Terms.Bucket> brandBuckets = brandTerms.getBuckets();
                if(brandBuckets != null){
                    brandBuckets.forEach(bucket -> memberIdSet.add(Long.valueOf(String.valueOf(bucket.getKey()))));
                    return new ArrayList<>(memberIdSet);
                }
            }
            return null;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}